package com.woniuxy.permission.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniu.commons.util.JwtUtil;
import com.woniu.commons.util.RedisKey;
import com.woniu.dto.SelectAllDto;
import com.woniu.form.*;
import com.woniu.zsd.commons.core.model.Result;
import com.woniuxy.permission.entity.Permission;
import com.woniuxy.permission.service.IPermissionService;
import com.woniuxy.permission.utils.OSSUtil;
import com.woniu.commons.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理原详情表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-05-13
 */
@RestController
@RequestMapping("/permission")
@Api(tags = "管理员模块")
public class  PermissionController {
    @Resource
    private JwtUtil  jwtUtil;
    @Autowired
    private TokenUtil tokenUtil;
    @Resource
    private IPermissionService permissionService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result login(@RequestBody LoginForm lf, HttpServletResponse response) throws Exception {
        //登录
        Permission adminInfo = permissionService.login(lf);
        //生成双token
        HashMap<String, Object> body = new HashMap<>();
        body.put("id", adminInfo.getId());
        body.put("role", adminInfo.getRoleId());
        String accessToken = jwtUtil.createToken(body, 30);
        String refreshToken = jwtUtil.createToken(body, 60 * 24);
        //将refreshToken保存到redis中
        stringRedisTemplate.opsForValue().set(RedisKey.ADMIN_REFRESH_TOKEN_KEY(accessToken),refreshToken,60 * 24, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(RedisKey.ADMIN_ACCESS_TOKEN_KEY(adminInfo.getId()), accessToken, 30, TimeUnit.MINUTES);
        //在redis中保存过期时
        stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_TIME_OUT(accessToken), String.valueOf(body.get("id")), 30, TimeUnit.MINUTES);

        response.setHeader("Access-Control-Expose-Headers","token");
        response.setHeader("token", accessToken);
        return Result.getResult().setMsg("登录成功");
    }

    @PostMapping("/insertAdminInfo")
    @ApiOperation("添加工作人员信息")
    public Result insertAdminInfo(@ApiParam(name = "aif", value = "添加员工表单")@RequestBody AdminInfoForm aif,@RequestHeader("token")String token) throws Exception {

        permissionService.insertAdminInfo(aif);
        return Result.getResult().setMsg("添加成功");
    }
    @PostMapping("/updateAdminInfo")
    @ApiOperation("修改工作人员信息")
    public Result updateAdminInfo(@ApiParam(name = "uaif", value = "修改工作人员信息表单")@RequestBody UpdateAdminInfoForm uaif) {
        // 调用服务层方法进行校验
        boolean isDuplicate = permissionService.checkDuplicateInfo(uaif.getAdminId(), uaif.getId(), uaif.getPhone());
        if (isDuplicate) {
            return Result.getResult().setMsg("账号或手机号已存在").setCode(400);
        }
        permissionService.updateAdminInfo(uaif);
        return Result.getResult().setMsg("修改成功");
    }
    @DeleteMapping("/deleteAdminInfoById")
    @ApiOperation("删除工作人员信息")
    public Result deleteAdminInfoById(@RequestParam Integer adminId,@RequestHeader String token) {
        permissionService.deleteAdminInfoById(adminId);
        return Result.getResult().setMsg("删除成功");
    }
    @PostMapping("/selAll")
    @ApiOperation("查询所有工作人员信息")
    public Result<IPage<SelectAllDto>> selAll(@RequestBody SelectAllForm selectAllForm) {
        IPage<SelectAllDto> adminInfoList = permissionService.selAll(selectAllForm);
        return new Result<IPage<SelectAllDto>>().setData(adminInfoList).setMsg("查询成功").setCode(200);
    }

    @PutMapping("/updatePassword")
    @ApiOperation("修改密码")
    public Result updatePassword(@RequestBody UpdatePasswordForm updatePasswordForm, @RequestHeader String token) throws Exception {
        // 从 token 中获取 adminId
        Integer adminId = tokenUtil.getAdminId(token);

        // 修改密码
        boolean isSuccess = permissionService.updatePassword(adminId, updatePasswordForm);
        if (isSuccess) {
            return Result.getResult().setMsg("密码修改成功");
        } else {
            return Result.getResult().setMsg("密码修改失败").setCode(400);
        }
    }
    /**
     * 根据token查询自己的所有信息
     */
    @GetMapping("/selInfoByToken")
    @ApiOperation("根据token查询自己的所有信息")
    public Result<Permission> selInfoByToken(@RequestHeader("token") String token) {
        System.out.println(token);
        Integer adminId = tokenUtil.getAdminId(token);
        Permission permission = permissionService.getFindById(adminId);
        return new Result<Permission>().setData(permission).setMsg("查询成功");
    }
    @GetMapping("/getCustomerService")
    @ApiOperation("随机获取客服id")
    public Result<Integer> getCustomerService(@ApiParam (value = "用户id") @RequestParam("userId") Integer userId){
        Integer customerServiceId = permissionService.getCustomerService();
        return new Result<Integer>().setData(customerServiceId).setMsg("获取客服成功");
    }


    /**
     * 获取本类里面所有的接口并支持resorcecontroller类调用
     */
    // 存储所有接口路径及其对应的描述信息
    private static final Map<String, String> PERMISSION_URLS = new HashMap<>();

    // 静态代码块，初始化接口路径及其描述信息
    static {
        try {
            // 获取 PermissionController 类的所有方法
            Method[] methods = PermissionController.class.getDeclaredMethods();
            for (Method method : methods) {
                // 检查是否有 @PostMapping 或 @GetMapping 注解
                if (method.isAnnotationPresent(PostMapping.class)) {
                    PostMapping postMapping = method.getAnnotation(PostMapping.class);
                    String[] paths = postMapping.value();
                    for (String path : paths) {
                        // 获取 @ApiOperation 注解的描述信息
                        String description = method.getAnnotation(ApiOperation.class).value();
                        PERMISSION_URLS.put("/permission" + path, description);
                    }
                } else if (method.isAnnotationPresent(GetMapping.class)) {
                    GetMapping getMapping = method.getAnnotation(GetMapping.class);
                    String[] paths = getMapping.value();
                    for (String path : paths) {
                        // 获取 @ApiOperation 注解的描述信息
                        String description = method.getAnnotation(ApiOperation.class).value();
                        PERMISSION_URLS.put("/permission" + path, description);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 提供一个方法，用于获取所有接口路径及其描述信息
    public static Map<String, String> getPermissionUrls() {
        // 创建 PERMISSION_URLS 的副本以避免修改原始映射
        Map<String, String> permissionUrlsCopy = new HashMap<>(PERMISSION_URLS);

        // 移除登录接口和根据 token 查看自己信息的接口
        permissionUrlsCopy.remove("/permission/login");
        permissionUrlsCopy.remove("/permission/selInfoByToken");

        return permissionUrlsCopy;
    }

}
